import useLimsStore from '@/store/modules/lims'
import { shareJclbList } from '@/api/store/jclb'
import { getUnitList } from '@/api/store/unit'
import { getLineResult } from "@/api/common";
import { extractNumbersFromString, isNumber, getFormulaResult, getDecimalLength, isTrueCondtion, setLineRrule, roundHalfEvenByPoint, getExpressValue, getRealValue } from "@/utils/formula";
let tableConfig, $form, proxy;
/**
* 获取检测类别数据
*/
export function useJclb() {
    const res = ref({});
    return (() => {
        res.value.jclbList = [];
        const jclbList = useLimsStore().jclbList;
        if (jclbList && jclbList.length != 0) {
            res.value.jclbList = jclbList;
        } else {
            shareJclbList().then(resp => {
                res.value.jclbList = resp.data
                useLimsStore().setJclb(res.value.jclbList);
            })
        }
        return toRefs(res.value);
    })()
}

/**
* 获取检测类别数据
*/
export function useUnit() {
    const res = ref({});
    return (() => {
        res.value.unit = [];
        const units = useLimsStore().unit;
        if (units.length != 0) {
            res.value.unit = units;
        } else {
            getUnitList().then(resp => {
                res.value.unit = resp.data
                useLimsStore().setUnit(res.value.unit);
            })
        }
        return toRefs(res.value);
    })()
}

/**
 * 查询并计算空白样品的空白浓度
 */
export function addSignAverage() {
    let $form = $("#dataForm");
    let $samples = $form.find("tr[sampleType=1]");
    if ($samples.length == 0) return;
    //试样浓度
    let A = "1703989740973662210";
    //空白浓度
    let A0 = "1703989792139976705";
    $samples.each(function (i) {
        let $this = $(this);
        const jcxmId = $this.data("jcxm-id");
        if(!jcxmId){
            return;
        }
        let $A = $this.find("td[name='" + A + "']");
        if ($A.length == 0) return false;
        let $A0 = $this.find("td[name='" + A0 + "']");
        if ($A0.length == 0) return false;
        eventSignAverage($this, $A, $A0, jcxmId);
    });
}

//有证标准物质表计算是否合格
export function eventBzwzIsHg($trs) {
    $trs.each(function () {
        const $tr = $(this);
        const $isHg = $tr.find("select[name='1733398490884878338']");
        if ($isHg.length == 0) return;
        //标准值
        const $bzValue = $tr.find("td[name='1756881062197518341']");
        //不确定度
        const $notValue = $tr.find("td[name='1756881062197518343']");
        //不确定度单位
        const $notValueUnit = $tr.find("td[name='1756881062197518344']");
        const $resultValue = $tr.find("td[name='1756881062197518339']");
        if ($notValueUnit.length == 0 || $notValue.length == 0 || $bzValue.length == 0 || $resultValue.length == 0) {
            return;
        }
        try {
            $resultValue.attr("isResult", 1);
            const resultValue = getRealValue($resultValue, $resultValue.text());
            if (resultValue < 0) return;
            let notValue = extractNumbersFromString($notValue.text());
            notValue = $notValueUnit.text() == '%' ? notValue / 100 : notValue;
            const minValue = parseFloat($bzValue.text()) - notValue;
            const maxValue = parseFloat($bzValue.text()) + notValue;
            let isHg = resultValue >= minValue && resultValue <= maxValue ? 0 : 1;
            $isHg.val(isHg);
        } catch (e) {
        }
    });
}
/**
 * 计算空白样品的平均值
 * @param {*} $A 试样浓度
 * @param {*} trIndex 试样浓度所有的行号（从1开始）
 */
function eventSignAverage($tr, $A, $A0, jcxmId) {
    $A.data("blur", true);
    $A.blur(function () {
        let AValue = $.trim($(this).text());
        if (AValue.length == 0) return false;
        let t = 1;
        let AName = $(this).attr("name");
        let express = AValue;
        let $twoA = $tr.prev("[sampleType=1]").find("td[name='" + AName + "']");
        if($twoA.length == 0 || $twoA.parent().data("jcxm-id") != jcxmId){
            $twoA = $tr.next("[sampleType=1]").find("td[name='" + AName + "']");
        }
        if ($twoA.length > 0 && $twoA.parent().data("jcxm-id") == jcxmId) {
            let twoAValue = $.trim($twoA.text());
            if (twoAValue.length == 0) return false;
            express += "+" + twoAValue;
            t++;
        }
        const formula = { isResult: 1, paramList: [{ value: AValue }],ruleList: [{ruleConditionId:7,ruleTypeId:1,xyId:1}] }
        let resultValue;
        try {
            resultValue = getFormulaResult($A0, formula, "(" + express + ")/" + t);
        } catch (e) {
            $A0.text('');
        }
        if (t > 1) {
            $twoA.parent().find("td[name='" + $A0.attr("name") + "']").text(resultValue);
        }
        $tr.find("td[name='" + $A0.attr("name") + "']").text(resultValue);
    });
}

export function addTableEvent($form) {
    instrumentCodeChange($form);
}

/**
 * 仪器编号下拉列表改变事件用于回显仪器信息
 * @param {jquery表对象} $form 
 */
function instrumentCodeChange($form) {
    //1704723165634019329:仪器型号固定控件id
    let $code = $form.find("td[name='1704723165634019329']");
    //1704723078786760705:仪器名称固定控件id
    let $name = $form.find("td[name='1704723078786760705']");
    if ($code.length == 0 || $name.length == 0) return;
    //仪器编号下拉列表
    let $number = $form.find("select[name='1704697349730684929']");
    if ($number.length == 0) return;
    //1704697349730684929:仪器编号下拉列表控件id(固定控件)
    $number.change(function () {
        if (!this.value) return true;
        let instrumentData = $(this).find("option:selected").data("json");
        if ($code.length > 0) {
            //1704711380252184578:仪器型号数据集id
            $code.text(instrumentData["1704711380252184578"]);
        }
        if ($name.length > 0) {
            //1704711380252184578:仪器名称数据集id
            $name.text(instrumentData["1704711380252184579"]);
        }
    });
    $number.change();
}

/**
 * 给控件注册焦点离开事件用于根据条件值自动判断检测限值并显示在表单中。
 */
export function addHandleCondtionEvent($component, $form, handleJcxmList, checkLimitCondtionList) {
    //当前控件已经绑定了blur事件。
    //条件暂时不判断
    // if($component.data("events")["blur"]) return;
    // $component.blur(function(){
    //     setFormCheckLimit($form, handleJcxmList, checkLimitCondtionList);
    // });
}

/**
 * 通过前处理查询检出限，这个函数有2个函数调用，这样显示是不合理，但目前未找到更好的解决方案。
 * 第1个是前处理下拉列表（首次加载如果有1个前处理也会默认调用），第2个是showTable()后调用。
 * 因这2个函数是并行的理论情况下会存在同时调用的可能，但如果前处理下拉列表中只有1个前处理的情况下默认调用，因此接口请求比较小所以$form大概率是空的，所以真正调用的会是showTable()函数。
 */
export function handleJcxmCheckLimitData(jcxmCheckLimitParams) {
    if (!$form) return;
    //1696048841341812737：检出限id
    let $checkLimit = $form.find("td[name=\"1696048841341812737\"]");
    setTrCheckLimit();
    const headCheckLimitValues = setHeadCheckLimit();
    if ($checkLimit.length == 0) return;
    $checkLimit.each(function () {
        const $cuCheckLimit = $(this);
        const $tr = $cuCheckLimit.parents("tr:first.childTr");
        if ($tr.length > 0) {
            return;
        }
        $cuCheckLimit.html(headCheckLimitValues);
    });
}

function setHeadCheckLimit() {
    const checkLimitList = tableConfig.distinctCheckLimitListByJcxm;
    let str = "";
    let i = 0;
    const $headCheckLimitUnit = $form.find("td[name='1786087373401313281']");
    let isSameCheckLimitUnit = $headCheckLimitUnit.length > 0;
    for (const item of checkLimitList) {
        if (i > 0) {
            str += "、";
        }
        str += item.checkLimitValue;
        if (item.checkLimitUnit) {
            const checkLimitUnit = proxy.getSupAndSub(item.checkLimitUnit);
            str += checkLimitUnit;
            if (isSameCheckLimitUnit && i > 0) {
                const prevCheckLimit = checkLimitList[i-1];
                if (prevCheckLimit.checkLimitUnit != item.checkLimitUnit) {
                    isSameCheckLimitUnit = false;
                }
            }
        } else if (isSameCheckLimitUnit) {
            isSameCheckLimitUnit = false;
        }
        i++;
    }
    if (isSameCheckLimitUnit && checkLimitList.length > 0) {
        $headCheckLimitUnit.html(proxy.getSupAndSub(checkLimitList[0].checkLimitUnit));
    }else if($headCheckLimitUnit.length > 0){
        $headCheckLimitUnit.html('');
    }
    return str;
}

function setTrCheckLimit() {
    const $trs = $form.find("tr.childTr");
    const checkLimitList = tableConfig.sampleCheckLimitList;
    $trs.each(function () {
        const $tr = $(this);
        const sampleId = $tr.data("sjid");
        if (!sampleId) return false;
        let checkLimit = checkLimitList.filter((item) => {
            //甲烷、非甲烷、动植物油的表sjid是合并的，sampleId:"1762850697256136709,1762850697314856962
            const index = (sampleId + "").indexOf(item.sJId);
            if (index != -1) {
                if (!item.checkLimitTableId) {
                    item.checkLimitTableId = 'ND';
                }
                return true;
            }
            return false;
        });
        if (checkLimit.length == 0) return;
        $tr.data("checkData", checkLimit);
        const $checkLimit = $tr.find("td[name=\"1696048841341812737\"]");
        if ($checkLimit.length == 0) return;
        checkLimit = checkLimit[0];
        let str = checkLimit.checkLimitValue;
        if (checkLimit.checkLimitUnit) {
            str += proxy.getSupAndSub(checkLimit.checkLimitUnit);
        }
        $checkLimit.html(str);
    });

}

/**
 * 
 * @param {模板Form对象} $parent 如果检出限在表头上即为$form,如果检出限为子表行的某一列则为$tr 
 * @param {前处理检测项目数据主要包含条件和检出限值} handleJcxmList 
 * @param {检测限条件中的对应的控件列表需要在模板管理中的前处理选项卡那设置对应关系} checkLimitCondtionList 
 */
export function setFormCheckLimit($parent, handleJcxmList, checkLimitCondtionList) {
    // if (checkLimitCondtionList) {
    //     for (let condition of checkLimitCondtionList) {
    //         //如果检出限有条件，则先查询条件对应的控件的值。检测限条件：稀释位数=10ml时检出限为：0.5
    //         let value = $parent.find("td[name='" + condition.componentId + "']").text();
    //         if (value) {
    //             condition.value = value;
    //         } else {
    //             delete condition.value;
    //         }
    //         addHandleCondtionEvent($parent, handleJcxmList, checkLimitCondtionList);
    //     }
    // }
    if (handleJcxmList) {
        //1696048841341812737:检出限控件id
        let $checkLimit = $parent.find("td[name=\"1696048841341812737\"]");
        let checkLimit = "";
        let errorMsg = "";
        let validCheckDataList = [];
        for (const item of handleJcxmList) {
            if (handleJcxmList.length == 1) {
                if (!item.orgCheckLimit) {
                    errorMsg += "、" + item.jcxmName;
                } else {
                    $checkLimit.html(item.unitName ? item.orgCheckLimit + proxy.getSupAndSub(item.unitName) : item.orgCheckLimit);
                    //将检出限单位放到缓存中，保存时传到后端。
                    if (item.unitName) {
                        item.checkLimitUnit = item.unitName;
                    }
                    validCheckDataList.push(item);
                    $checkLimit.data("checkData", validCheckDataList);
                }
                break;
            }
            //查询多个检测项目的检出限，需要显示检测项目用于区分，例如：氨氮：0.5mg、总氮：0.6mg
            if (item.orgCheckLimit) {
                checkLimit += "、" + item.jcxmName + ":";
                checkLimit += item.orgCheckLimit;
                if (item.unitName) {
                    item.checkLimitUnit = item.unitName;
                    checkLimit += proxy.getSupAndSub(item.unitName)
                }
                validCheckDataList.push(item);
            } else {
                errorMsg += "、" + item.jcxmName;
            }
            if (item.params.errorMsg) {
                errorMsg += " " + item.params.errorMsg;
            }
            //以后按条件的需求不清楚先注释。
            // if (!item.condition || item.condition == 'φφφ') {
            //     if (handleJcxmList.length == 1) {//如果返回的结果只有一个检出限则直接显示。
            //         if (!item.orgCheckLimit) {
            //             $checkLimit.text("无");
            //         } else {
            //             $checkLimit.text(item.orgCheckLimit + item.unitName);
            //             //将检出限单位放到缓存中，保存时传到后端。
            //             $checkLimit.data("checkLimitUnit", item.unitName)
            //         }
            //         break;
            //     }
            //     //查询多个检测项目的检出限，需要显示检测项目用于区分，例如：氨氮：0.5mg、总氮：0.6mg
            //     checkLimit += "、" + item.jcxmName + ":";
            //     if (item.orgCheckLimit) {
            //         checkLimit += item.orgCheckLimit + item.unitName;
            //     } else {
            //         checkLimit += "无";
            //     }
            // } else if (checkLimitCondtionList) {
            //     for (let condition of checkLimitCondtionList) {
            //         if (condition.value) {
            //             item.condition = item.condition.replace(eval("/" + condition.conditionName + "/g"), condition.value);
            //         }
            //     }
            //     if (isTrueCondtion(item.condition)) {
            //         if (handleJcxmList.length == 1) {
            //             if (!item.orgCheckLimit) {
            //                 $checkLimit.text("无");
            //             } else {
            //                 $checkLimit.text(item.orgCheckLimit + item.unitName);
            //                 //将检出限单位放到缓存中，保存时传到后端。
            //                 $checkLimit.data("checkLimitUnit", item.unitName)
            //             }
            //             break;
            //         }
            //         //查询多个检测项目的检出限，需要显示检测项目用于区分，例如：氨氮：0.5mg、总氮：0.6mg
            //         checkLimit += "、" + item.jcxmName + ":";
            //         if (item.orgCheckLimit) {
            //             checkLimit += item.orgCheckLimit + item.unitName;
            //         } else {
            //             checkLimit += "无";
            //         }
            //     }
            // }
        }
        if (errorMsg.length > 0) {
            proxy.$modal.msgWarning("未找到" + errorMsg.substring(1) + "检出限值！");
        }
        if (checkLimit.length > 0) {
            if (checkLimit.startsWith("、")) {
                checkLimit = checkLimit.substring(1);
            }
            $checkLimit.html(checkLimit);
            $checkLimit.data("checkData", validCheckDataList);
        }
    }
}

export function eventLine($form, callback) {
    const $x = $form.find("td[name='1708421919264432129']");
    if ($x.length == 0) return;
    const $y = $form.find("td[name='1708422032481280001']");
    if ($y.length == 0) return;
    if ($x.length != $y.length) {
        alert("x和y的数量必须相同！");
        return;
    }
    //回归方程
    const $equation = $form.find("td[name='1704039502909349889']");
    if ($equation.length == 0) return;
    $equation.text('');
    const $a = $form.find("td[name='1704038809393766401']");
    const $b = $form.find("td[name='1704038862384603138']");
    const $r2 = $form.find("td[name='1704038914603687938']");
    $a.text('');
    $b.text('');
    $r2.text('');
    let xArray = [];
    let yArray = [];
    $x.each(function () {
        let value = $.trim($(this).text());
        if (!value || isNaN(value)) return true;
        if (value.indexOf('.') == -1)
            value += ".0";
        xArray.push(value);
    });
    $y.each(function () {
        let value = $.trim($(this).text());
        if (!value || isNaN(value)) return true;
        if (value.indexOf('.') == -1)
            value += ".0";
        yArray.push(value);
    });
    if (xArray.length != yArray.length) {
        alert("x和y的数量必须相同！");
        return;
    }
    let param = { xList: xArray, yList: yArray }
    getLineResult(param).then(res => {
        let resultData = res.data;
        let symbol = resultData.a.toString().startsWith("-") ? "" : "+";
        let pointCount = 4;
        if ($a.length > 0 && typeof $a.data("pointcount") == 'number') {
            pointCount = $a.data("pointcount");
        }
        const aValue = roundHalfEvenByPoint(resultData.a, pointCount);
        if ($b.length > 0 && typeof $b.data("pointcount") == 'number') {
            pointCount = $b.data("pointcount");
        }
        const bValue = roundHalfEvenByPoint(resultData.b, pointCount);
        $equation.text("y=" + bValue + "x" + symbol + aValue);
        if ($a.length > 0) {
            $a.text(aValue);
        }
        if ($b.length > 0) {
            $b.text(bValue);
        }
        if ($r2.length > 0) {
            $r2.text(setLineRrule(resultData.r2));
        }
        callback();
    });
}

//重置表单防止多个表单切换千万引用的$form混乱。
export function resetData() {
    $form = null;
    tableConfig = null;
}
/**
 * 表单注册函数
 * @param {jquery表对象} $form 
 * @param {表单配置数据} tableData 
 */
export function registerEvent(proxyObj, $form1, tableConfig1, jcxmCheckLimitParams) {
    proxy = proxyObj;
    $form = $form1;
    tableConfig = tableConfig1;
    if (tableConfig.sampleCheckLimitList) {
        handleJcxmCheckLimitData();
    }
    //添加计算空白平均值的事件。
    addSignAverage();
    addTableEvent($form);
    lineA();
}

export function lineA() {
    if (tableConfig.modelType != 7) return;
    const $A = $form.find("td[name='1709175404014903297']");
    if ($A.length > 0) {
        const $y = $form.find("td[name='1708422032481280001']");
        if ($y.length == 0) return;
        let $firstA;
        $A.each(function (i) {
            let $that = $(this);
            if (i == 0) $firstA = $that;
            $that.data("$y", $(this).parent().find("td[name='1708422032481280001']"));
            $that.data("blur", true);
            $that.on("blur", function () {
                if (!isNumber($firstA.text()) || !isNumber($(this).text())) {
                    $(this).data("$y").text('');
                    return;
                }
                let firstAValue = parseFloat($firstA.text());
                let AValue = parseFloat($(this).text());
                let value = getExpressValue(AValue + "-" + firstAValue);
                value = roundHalfEvenByPoint(value, getDecimalLength($(this).text()));
                $(this).data("$y").text(value);
            })
        });
    }
}

export function setIsHg($comId, resultValue) {
    if (!isNumber(resultValue)) {
        return;
    }
    const $tr = $comId.parents("tr:first");//当前行
    const $isHg = $tr.find("select[name='1733398490884878338']");//是否合格对象
    if ($isHg.length == 0) return;
    const $fw = $tr.find("td[name='1733824627435909122']");//标准范围对象
    if ($fw.length == 0) return;
    const fwNumbers = extractNumbersFromString($fw.text());
    if (!fwNumbers || fwNumbers.length == 0) return;
    if (!resultValue || resultValue == '') {
        $isHg.val('0');
    }
    resultValue = parseFloat(resultValue);
    const comId = $comId.attr("name");
    if (comId == '1734081527607996417') {//加标回收率
        if (resultValue < fwNumbers[0] || (fwNumbers.length == 2 && resultValue > fwNumbers[1])) {
            $isHg.val('1');
        } else {
            $isHg.val('0');
        }
        return;
    }
    //相对偏差值 1760269228531048450:校准分析结果表中的相对偏差控件,1799248312938131458:穿透表中的吸附率
    if (comId == '1703701390802886658' || comId == '1760269228531048450' || comId == '1799248312938131458') {
        if (resultValue <= fwNumbers[0]) {
            $isHg.val('0');
        } else {
            $isHg.val('1');
        }
        return;
    }
}

export function handleSubAndSup($form, proxyObj) {
    $form.find("td").each(function (i) {
        if ($(this).html().indexOf("^") != -1 || $(this).html().indexOf("@") != -1) {
            $(this).data("v-value",$(this).text());
            $(this).html(proxyObj.getSupAndSub($(this).text()));
        }
    });
}

//读取样品编号1对多行中跨行的数据。
export function getRowspanValue($form,$tr,name){
    if($tr.length == 0 || !name){
        return {length:0};
    }
    const groupId = $tr.attr("group_id");
    if(!groupId) {
        return {length:0};
    }
    let $matchValue;
    while(true){
        $tr = $tr.prev();
        if($tr.length == 0 || !$tr.attr("group_id") || $tr.attr("group_id") != groupId){
            break;
        }
        let $td = $tr.find("td[name='" + name + "']");
        if($td.length == 0){
            continue;
        }
        $matchValue = $td;
        break;
    }
    if(!$matchValue){
        $matchValue = $form.find("td[name='" + name + "']");
    }
    return $matchValue;
}